﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using CrystalDecisions.CrystalReports.Engine;
using System.Reflection;
using System.IO;


namespace Plugin
{
    public class Config
    {
        /// <summary>
        /// 服务名称
        /// </summary>
        private string _ServiceName = "504所装箱运输单打印";

        public string ServiceName
        {
            get
            {
                return _ServiceName;
            }
        }

        /// <summary>
        /// 插件版本
        /// </summary>
        private string _DLLVersion = "1.0";

        public string DLLVersion
        {
            get
            {
                return _DLLVersion;
            }
        }

        /// <summary>
        /// 运行间隔，默认60秒执行一次
        /// </summary>
        private int _RunInterval = 60;

        public int RunInterval
        {
            get
            {
                return _RunInterval;
            }
        }

        /// <summary>
        /// 显示设置窗体
        /// </summary>
        public void ShowConfig()
        {
            frmConfig newFrmConfig = new frmConfig();
            newFrmConfig.Show();
        }
    }

    public class Service
    {
        private SqlTools sqt;

        public Service()
        {
            //初始化SQL查询对象
            sqt = new SqlTools(GeneralTools.GetConnectionString("TPAMain"));
        }

        public void Start()
        {
            //检查当前是否有504所销货单
            string strTmpSelectString = "select 销货单号,订单编号,规格型号,数量 from (select xhb001 销货单号,htb027 订单编号,xhb003 规格型号,xhb008 数量 from orxha_table,orxhb_table,gxck_table,htb_table where xha001=xhb001 and left(xhb014,12)=gxck001 and gxck010=htb001 and gxck011=htb002 and xha007 like '504%' and xha013='Y' and xha001 not in (select 销货单号 from zxysd_504) and xhb032='603' union all select xhb001 销货单号,htb027 订单编号,xhb003 规格型号,xhb008 数量 from orxha_table,orxhb_table,TPAMainTZ.dbo.gxck_table,htb_table where xha001=xhb001 and left(xhb014,12)=gxck001 and gxck010=htb001 and gxck011=htb002 and xha007 like '504%' and xha013='Y' and xha001 not in (select 销货单号 from zxysd_504) and xhb032='601') a order by 订单编号,规格型号";
            DataTable tmpdt = sqt.GetData(strTmpSelectString);
            if (tmpdt != null && tmpdt.Rows.Count > 0)
            {
                try
                {
                    List<DataSet> lstDs = new List<DataSet>();
                    List<string> lstXhdh = new List<string>();
                    StringBuilder tmpsb = new StringBuilder();
                    //装箱审核人
                    GeneralTools.GetPrivateProfileString("Config", "PackageMan", string.Empty, tmpsb, 256, System.Windows.Forms.Application.StartupPath + "\\Plugin\\Print_Zxysd_504_Config.ini");
                    string strPackageMan = tmpsb.ToString();
                    //生成报表数据
                    string strTmpOrderID ="-1";
                    //数据集
                    DataSet ds = new DataSet();
                    //主表
                    DataTable dt = new DataTable();
                    //装箱日期
                    string strPackageDate = sqt.GetServerDate();
                    strPackageDate = strPackageDate.Substring(0, 4) + "年" + strPackageDate.Substring(4, 2) + "月" + strPackageDate.Substring(6, 2) + "日";
                    int iCount = 1;
                    for (int i = 0; i < tmpdt.Rows.Count; i++)
                    {
                        if (!tmpdt.Rows[i]["订单编号"].Equals(strTmpOrderID))
                        {
                            //当前行订单编号与缓存订单编号单号不一致时，保存当前缓存数据，更新销货单号
                            if (dt.Rows.Count > 0)
                            {
                                lstDs.Add(ds);
                            }
                            //声明新数据表
                            ds = new DataSet();
                            dt = new DataTable();
                            ds.Tables.Add(dt);
                            dt.TableName = "ReportData";
                            dt.Columns.Add("订单编号");
                            dt.Columns.Add("发货单位");
                            dt.Columns.Add("序号");
                            dt.Columns.Add("名称");
                            dt.Columns.Add("规格型号");
                            dt.Columns.Add("单位");
                            dt.Columns.Add("数量");
                            dt.Columns.Add("质量等级");
                            dt.Columns.Add("随货资料份数");
                            dt.Columns.Add("装箱审核人");
                            dt.Columns.Add("装箱日期");
                            //缓存订单编号
                            strTmpOrderID = GeneralTools.GetString(tmpdt.Rows[i]["订单编号"], string.Empty);
                            //初始化行标
                            iCount = 1;
                        }
                        //将当前行添加到数据表
                        DataRow tmpdr = dt.NewRow();
                        tmpdr["订单编号"] = tmpdt.Rows[i]["订单编号"];
                        tmpdr["发货单位"] = "成都宏明电子科大新材料有限公司";
                        tmpdr["序号"] = iCount;
                        tmpdr["名称"] = "电容器";
                        //拆分型号规格
                        string strTmpModel = GeneralTools.GetString(tmpdt.Rows[i]["规格型号"],string.Empty );
                        string strClass = string.Empty;
                        if (strTmpModel .Contains("-"))
                        {
                            strClass = strTmpModel.Substring(0, strTmpModel.IndexOf('-'));
                            strTmpModel = strTmpModel.Substring(strClass.Length + 1, strTmpModel.Length - strClass.Length - 1);
                        }
                        tmpdr["规格型号"] = strTmpModel;
                        tmpdr["单位"] = "只";
                        tmpdr["数量"] = tmpdt.Rows[i]["数量"];
                        tmpdr["质量等级"] = strClass;
                        tmpdr["随货资料份数"] = 2;
                        tmpdr["装箱审核人"] = strPackageMan;
                        tmpdr["装箱日期"] = strPackageDate;
                        if (!(lstXhdh.IndexOf(GeneralTools.GetString(tmpdt.Rows[i]["销货单号"], string.Empty))>=0))
                            lstXhdh.Add(GeneralTools.GetString(tmpdt.Rows[i]["销货单号"], string.Empty));
                        dt.Rows.Add(tmpdr);
                        iCount++;
                        if (i == tmpdt.Rows.Count - 1)
                        {
                            //如果已读取到最后一行，则保存数据表
                            lstDs.Add(ds);
                        }
                    }
                    //处理主表记录，如超过10行，则增加子表
                    for(int i=0;i<lstDs.Count;i++)
                    {
                        if (lstDs[i].Tables["ReportData"].Rows .Count >18)
                        {
                            DataTable subdt = new DataTable();
                            subdt.TableName = "SubReportData";
                            subdt.Columns.Add("订单编号");
                            subdt.Columns.Add("发货单位");
                            subdt.Columns.Add("序号");
                            subdt.Columns.Add("名称");
                            subdt.Columns.Add("规格型号");
                            subdt.Columns.Add("单位");
                            subdt.Columns.Add("数量");
                            subdt.Columns.Add("质量等级");
                            subdt.Columns.Add("随货资料份数");
                            lstDs[i].Tables.Add(subdt);
                            //将数据添加到子表
                            for(int k=0;k< lstDs[i].Tables["ReportData"].Rows.Count;k++)
                            {
                                DataRow tmpdr = subdt.NewRow();
                                tmpdr["订单编号"] = lstDs[i].Tables["ReportData"].Rows[k]["订单编号"];
                                tmpdr["发货单位"] = lstDs[i].Tables["ReportData"].Rows[k]["发货单位"];
                                tmpdr["序号"] = lstDs[i].Tables["ReportData"].Rows[k]["序号"];
                                tmpdr["名称"] = lstDs[i].Tables["ReportData"].Rows[k]["名称"];
                                tmpdr["规格型号"] = lstDs[i].Tables["ReportData"].Rows[k]["规格型号"];
                                tmpdr["单位"] = lstDs[i].Tables["ReportData"].Rows[k]["单位"];
                                tmpdr["数量"] = lstDs[i].Tables["ReportData"].Rows[k]["数量"];
                                tmpdr["质量等级"] = lstDs[i].Tables["ReportData"].Rows[k]["质量等级"];
                                tmpdr["随货资料份数"] = lstDs[i].Tables["ReportData"].Rows[k]["随货资料份数"];
                                subdt.Rows.Add(tmpdr);
                            }
                            //删除主表数据
                            for (int k = lstDs[i].Tables["ReportData"].Rows.Count-1; k >0; k--)
                            {
                                lstDs[i].Tables["ReportData"].Rows.RemoveAt(k);
                            }
                            //修改第一条记录数据
                            lstDs[i].Tables["ReportData"].Rows[0]["序号"] = string.Empty;
                            lstDs[i].Tables["ReportData"].Rows[0]["名称"] = string.Empty;
                            lstDs[i].Tables["ReportData"].Rows[0]["规格型号"] = "详见清单";
                            lstDs[i].Tables["ReportData"].Rows[0]["单位"] = string.Empty;
                            lstDs[i].Tables["ReportData"].Rows[0]["数量"] = string.Empty;
                            lstDs[i].Tables["ReportData"].Rows[0]["质量等级"] = string.Empty;
                            lstDs[i].Tables["ReportData"].Rows[0]["随货资料份数"] = string.Empty;
                        }
                    }
                    ReportDocument tmprd = new ReportDocument();
                    ReportDocument tmprd_sub = new ReportDocument();
                    tmpsb = new StringBuilder();
                    GeneralTools.GetPrivateProfileString("Config", "Printer", string.Empty, tmpsb, 256, System.Windows.Forms.Application.StartupPath + "\\Plugin\\Print_Zxysd_504_Config.ini");
                    string strTmpPrinterName = tmpsb.ToString();
                    GeneralTools.GetPrivateProfileString("Config", "CopyCount", "1", tmpsb, 256, System.Windows.Forms.Application.StartupPath + "\\Plugin\\Print_Zxysd_504_Config.ini");
                    int iCopyCount = GeneralTools.GetInt(tmpsb.ToString(), 1);
                    tmprd.Load(System.Windows.Forms.Application.StartupPath + "\\Plugin\\Report_504.rpt");
                    tmprd_sub.Load(System.Windows.Forms.Application.StartupPath + "\\Plugin\\Report_504_sub.rpt");
                    //打印
                    for (int i = 0; i < lstDs.Count; i++)
                    {
                        tmprd.SetDataSource(lstDs[i].Tables["ReportData"]);
                        tmprd.PrintOptions.PrinterName = strTmpPrinterName;
                        tmprd.PrintToPrinter(iCopyCount, false, 0, 0);
                        if (lstDs[i].Tables.Count >1)
                        {
                            //如果数据表数量大于1，说明有字表，打印子报表
                            tmprd_sub.SetDataSource(lstDs[i].Tables["SubReportData"]);
                            tmprd_sub.PrintOptions.PrinterName = strTmpPrinterName;
                            tmprd_sub.PrintToPrinter(iCopyCount, false, 0, 0);
                        }
                    }
                    //更新销货单打印记录
                    for(int i=0;i<lstXhdh.Count;i++)
                    {
                        sqt.DoCmdExecuteNonQuery("insert into zxysd_504 (销货单号) values ('" + lstXhdh[i] + "')");
                    }
                }
                catch (Exception ex)
                {
                    GeneralTools.ShowErrorMsg("出现错误：" + ex.Message);
                }
            }
        }
    }
}
